﻿using UnityEngine;
/// <summary>
/// 用于事件对象之间的通信.使用泛型，传递的数据可自定义
/// 一旦sander和receiver和传递的信息message确定则进行通信。只有对receiver属性进行赋值的时候才会进行确认
/// </summary>
[System.Serializable]
public class TMessage<T>
{
#region 字段
    [SerializeField]
    private T message;
    [SerializeField]
    private Sender<T> sender;
    [SerializeField]
    private Receiver<T> receiver;
#endregion

#region 构造器
    public TMessage(T mes,Sender<T> sender,Receiver<T> receiver)
    {
        message = mes;
        this.sender = sender;
        this.receiver = receiver;
        Confirm();//进行确认
    }

    public TMessage(T mes) : this(mes, null, null) { }

    public TMessage(T mes,Sender<T> sender) : this(mes, sender, null) { }

    public TMessage(T mes, Receiver<T> receiver) : this(mes,null, receiver) { }
    #endregion

#region 属性
    public T Message
    {
        get
        {
            return message;
        }

        set
        {
            message = value;
        
        }
    }

    public Sender<T> Sender
    {
        get
        {
            return sender;
        }

        set
        {
            sender = value;
          
        }
    }

    public Receiver<T> Reiver
    {
        get
        {
            return receiver;
        }

        set
        {
            receiver = value;
            Confirm();
        }
    }
#endregion

    /// <summary>
    /// 确认通信。当三个字段都不为空的时候说明已经建立通信。在此进行通信
    /// </summary>
    private void Confirm()
    {
        if (sender==null)
        {
            return;
        }
        if (receiver==null)
        {
            return;
        }
        if (message==null)
        {
            return;
        }
        receiver.Reveive(sender.Send());
    }
}
